#include <boost/thread/thread.hpp>
//#include <ofstream>
#include <string>
#include <ctime>
#include <queue>
#include <cstdio>
#include "log.h"

//static boost::thread_group ths;
static boost::thread_group thrd;

static int cur_date = 0;

static FILE * fp = NULL;

static bool isend = false;

struct log_t
{
  std::string str;
  time_t wtime;
};

typedef std::queue<log_t> logs_t;
static logs_t logs;


static void update_date()
{
  if(fp != NULL) fclose(fp);
  struct tm * loctime;
  {
    time_t wtime;
    time(&wtime);
    loctime = localtime(&wtime);
  }
  char fname[16];
  sprintf(fname, "data/log/%02d-%02d-%d.txt", loctime->tm_mday, loctime->tm_mon, loctime->tm_year + 1900);
  fp = fopen(fname, "a");
  if(fp == NULL) printf("ERROR!\n");
}

void log_thread()
{
  struct tm * loctime;
  {
    time_t wtime;
    time(&wtime);
    loctime = localtime(&wtime);
  }
  while(!isend)
  {
    boost::this_thread::sleep(boost::posix_time::seconds(30));
    if(loctime->tm_mday != cur_date) update_date();
    while(!logs.empty())
    {
      log_t& clog = logs.front();
      loctime = localtime(&clog.wtime);
      fprintf(fp, "%s\n", clog.str.c_str());
      logs.pop/*_front*/();
    }
  }
  

}

void startup()
{
  thrd.create_thread(&log_thread);
}

void put_log(const char * s)
{
  time_t walltime;
  time(&walltime);
  log_t log;
  log.str = s;
  log.wtime = walltime;
  logs.push(log);
}

void stop_log()
{
  isend = true;
  thrd.join_all();
  fclose(fp);
}
